package base

import (
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/base"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-api/service/base/user"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"regexp"
	"strconv"
)

type UserNewController struct {
	controller.BaseController
	userNewService user.UserNewServiceIface
}

func NewUserNewController(userNewService user.UserNewServiceIface) *UserNewController {
	return &UserNewController{
		userNewService: userNewService,
	}
}

// RegisterRouter
// 注册路由
func (c *UserNewController) RegisterRouter(g *gin.RouterGroup) {
	// 用户列表
	g.POST("/user/list", c.UserList)
	// 新增/更新用户
	g.POST("/user/save", c.UserSave)
	// 删除用户
	g.POST("/user/delete", c.UserDelete)
	// 禁止用户
	g.POST("/user/forbid", c.UserForbid)
	// 账号授权
	g.POST("/user/authorize", c.UserAuthorize)
	// 用户导入
	g.POST("/user/import", c.UserImport)
	// 用户信息
	g.GET("/user/detail", c.UserDetail)
	// 重设密码
	g.POST("/user/set-password", c.SetPassword)
	// 重置密码
	g.POST("/user/reset-password", c.ResetPassword)
	// 设置负责人/取消负责人
	g.POST("/user/set-department-header", c.SetDepartmentHeader)
	// 全量用户列表
	g.GET("user/all-user", c.allUser)
	// 全量用户带组织架构列表
	g.GET("user/org-and-all-user", c.getOrgAndAllUser)
	// 获取我负责区域下的用户
	g.GET("user/my-responsible-area-users", c.GetMyResponsibleAreaUserList)
}

func (c *UserNewController) SetDepartmentHeader(ctx *gin.Context) {
	param := &base.SetDepartmentHeaderParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "SetDepartmentHeader-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	//if param.UserId == 0 {
	//	c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "用户编号为空")
	//	return
	//}

	if param.OrgId == 0 {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "组织编号为空")
		return
	}

	//if param.ResponsibleType < 1 || param.ResponsibleType > 2 {
	//	c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数错误")
	//	return
	//}

	err := c.userNewService.SetDepartmentHeader(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "SetDepartmentHeader-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, nil)
}

func (c *UserNewController) ResetPassword(ctx *gin.Context) {
	param := &base.ResetPasswordParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "ResetPassword-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	if (param.Passwd == "") || (len(param.Passwd) < 8) || (len(param.Passwd) > 32) {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "密码长度8～32字符")
		return
	}

	err := c.userNewService.ResetPassword(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "ResetPassword-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, nil)
}

func (c *UserNewController) UserList(ctx *gin.Context) {
	param := &base.UserListParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "UserList-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	if param.OrgId == 0 {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "部门编号为空")
		return
	}

	list, page, err := c.userNewService.UserList(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "UserList-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	newList := make([]map[string]interface{}, 0)
	for _, item := range list {
		listMap := make(map[string]interface{})
		listMap["id"] = item.Id
		listMap["user_name"] = item.UserName
		listMap["position"] = item.Position
		listMap["email"] = item.Email
		listMap["mobile"] = item.Mobile
		listMap["orgs"] = item.Orgs
		listMap["roles"] = item.Roles
		listMap["status"] = item.Status
		listMap["org_full_name_list"] = item.OrgFullNameList
		newList = append(newList, listMap)
	}

	c.Success(ctx, map[string]interface{}{
		"list":      newList,
		"page":      page.Page,
		"page_size": page.PageSize,
		"total":     page.Total,
	})
}

func validatePhoneNumber(phoneNumber string) bool {
	// 使用正则表达式匹配手机号
	// 这个正则表达式匹配中国大陆地区的手机号，包括11位数字，以1开头
	pattern := `^1\d{10}$`
	matched, err := regexp.MatchString(pattern, phoneNumber)
	if err != nil {
		return false
	}
	return matched
}

func validateEmail(email string) bool {
	// 使用正则表达式匹配邮箱地址
	// 这个正则表达式匹配常见的邮箱格式
	pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
	matched, err := regexp.MatchString(pattern, email)
	if err != nil {
		return false
	}
	return matched
}

func (c *UserNewController) UserSave(ctx *gin.Context) {
	param := &base.User{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "UserSave-error: %+v", err)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	if (param.UserName == "") || (param.Mobile == "" || len(param.Mobile) != 11) || (len(param.OrgIds) == 0) || (len(param.RoleIds) == 0) {
		stark.Logger.Infof(ctx, "UserSave-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "缺少参数字段")
		return
	}

	isMobile := validatePhoneNumber(param.Mobile)
	if isMobile == false {
		stark.Logger.Infof(ctx, "UserSave-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "非法手机号")
		return
	}

	isEmail := validateEmail(param.Email)
	if param.Email != "" && isEmail == false {
		stark.Logger.Infof(ctx, "UserSave-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "非法邮箱")
		return
	}

	userId, err := c.userNewService.UserSave(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "UserSave-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, map[string]interface{}{
		"id": userId,
	})
}

func (c *UserNewController) UserDelete(ctx *gin.Context) {
	param := &base.UserDeleteParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "UserDelete-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	//if (param.LeaveUserId == 0) || (param.ReceiveUserId == 0) {
	//	stark.Logger.Infof(ctx, "UserDelete-param: %+v", param)
	//	c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "缺少参数")
	//	return
	//}
	if param.LeaveUserId == 0 {
		stark.Logger.Infof(ctx, "UserDelete-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "缺少参数")
		return
	}

	userId, err := c.userNewService.UserDelete(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "UserDelete-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, map[string]interface{}{
		"id": userId,
	})
}

func (c *UserNewController) UserForbid(ctx *gin.Context) {
	param := &base.UserForbidParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "UserForbid-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	if param.UserId == 0 {
		stark.Logger.Infof(ctx, "UserForbid-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "缺少用户编号")
		return
	}

	if (param.Status < 1) || (param.Status > 2) {
		stark.Logger.Infof(ctx, "UserForbid-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "缺少状态参数")
		return
	}

	err := c.userNewService.UserForbid(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "UserForbid-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, nil)
}

func (c *UserNewController) UserAuthorize(ctx *gin.Context) {
	param := &base.UserAuthorizeParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "UserAuthorize-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}

	if (param.UserId == 0) || (len(param.RoleIds) == 0) {
		stark.Logger.Infof(ctx, "UserAuthorize-param: %+v", param)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "缺少参数")
		return
	}

	err := c.userNewService.UserAuthorize(ctx, param)
	if err != nil {
		stark.Logger.Infof(ctx, "UserAuthorize-error: %+v, param: %+v", err, param)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, nil)
}

func (c *UserNewController) UserImport(ctx *gin.Context) {
	param := &base.UserImportParam{}
	if err := ctx.ShouldBind(param); err != nil {
		stark.Logger.Infof(ctx, "UserImport-error: %+v", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	if param.FilePath == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "文件路径为空")
		return
	}
	if param.FileName == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "文件名为空")
		return
	}

	resp, err := c.userNewService.UserImport(ctx, param)
	if err != nil {
		stark.Logger.Info(ctx, "UserImport-failed: "+err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}

// UserDetail 获取信息
func (c *UserNewController) UserDetail(ctx *gin.Context) {
	userIdStr := ctx.Query("user_id")
	userId, _ := strconv.Atoi(userIdStr)
	if userId == 0 {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "用户编号为空")
		return
	}
	detail, err := c.userNewService.UserDetail(ctx, int64(userId))
	if err != nil {
		stark.Logger.Info(ctx, "UserDetail-failed: "+err.Error())
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	data := map[string]interface{}{
		"id":          detail.Id,
		"user_name":   detail.UserName,
		"position":    detail.Position,
		"email":       detail.Email,
		"mobile":      detail.Mobile,
		"orgs":        detail.Orgs,
		"roles":       detail.Roles,
		"status":      detail.Status,
		"created_on":  detail.CreatedOn,
		"modified_on": detail.ModifiedOn,
	}

	c.Success(ctx, data)
}

// SetPassword 设置密码
func (c *UserNewController) SetPassword(ctx *gin.Context) {
	// 1. 校验参数
	request := base.SetPasswordRequest{}
	if err := ctx.ShouldBind(&request); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		stark.Logger.Info(ctx, "using-phone: "+err.Error())
		return
	}
	// 2. 设置密码
	resp, err := c.userNewService.SetPassword(ctx, &request)
	if err != nil {
		stark.Logger.Info(ctx, "set-password-failed: "+err.Error())
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}
	c.Success(ctx, resp)
	return
}

func (c *UserNewController) allUser(ctx *gin.Context) {
	resp, err := c.userNewService.GetAllUserList(ctx)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}

func (c *UserNewController) getOrgAndAllUser(ctx *gin.Context) {
	resp, err := c.userNewService.GetAllUserWithOrganization(ctx)
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	c.Success(ctx, resp)
}

func (c *UserNewController) GetMyResponsibleAreaUserList(ctx *gin.Context) {
	request := &base.GetAllUserRequest{}
	if err := ctx.ShouldBindQuery(request); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils.GetValidateErr(request, err))
		return
	}
	list, err := c.userNewService.GetMyResponsibleAreaUserList(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetMyResponsibleAreaUserList-error: %+v, param: %+v", err, request)
		grpcErr := rpc_client.GetGrpcError(err)
		c.Fail(ctx, grpcErr.GetCode(), grpcErr.GetMessage())
		return
	}

	c.Success(ctx, list)
}
